package com.dingwen.treasure.web.excption.handler.impl;

import com.dingwen.treasure.base.constant.ExceptionConstant;
import com.dingwen.treasure.base.exception.BaseExceptionHandler;
import com.dingwen.treasure.base.pojo.vo.Result;
import com.dingwen.treasure.base.pojo.vo.ResultGenerator;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Path;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 　ConstraintViolationExceptionHandlerImpl: validation 异常处理
 * 　@author dingwen
 * 　@date 2022/5/14$
 */
@Component("javax.validation.ConstraintViolationException")
public class ConstraintViolationExceptionHandlerImpl extends BaseExceptionHandler<Map<Path,String>> {
    /**
     * 根据异常构建统一返回结果
     *
     * @param exception 异常
     * @return result
     */
    @Override
    public Result<Map<Path,String>> buildResultByException(Exception exception) {
        ConstraintViolationException constraintViolation = (ConstraintViolationException) exception;
        Map<Path, String> errInfoMap = constraintViolation.getConstraintViolations()
                .stream()
                .collect(Collectors.toMap(ConstraintViolation::getPropertyPath, ConstraintViolation::getMessage));
        return ResultGenerator.genFailureResult(ExceptionConstant.METHOD_PARAM_EX, HttpStatus.BAD_REQUEST.value(), errInfoMap);
    }
}
